package zw.netty.server.Netty.Handler;

import com.alibaba.fastjson.JSON;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import zw.netty.server.Netty.NettyServer;
import zw.netty.server.pojo.Device;
import zw.netty.server.web.WsController;

import java.util.Date;

/**
 * 传感器适配器
 * 创建人:zhuwei
 * 邮箱:121203654@qq.com
 * 创建时间:2018-08-15 10:10
 */
public class SensorHandler extends SimpleChannelInboundHandler<String>{
    private SimpMessagingTemplate template;


    public SensorHandler(SimpMessagingTemplate template){
        this.template=template;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        try{
            if(msg.indexOf("body")!=-1){
                Device device=  JSON.parseObject(msg,Device.class);
                if(device.getName().equals("ODB")&&device.getBody().length()>10){
                    template.convertAndSend("/topic/odb",msg);
                }else if(device.getName().equals("50960")) {
                    template.convertAndSend("/topic/mpu6050",msg);
                }
            }else if(msg.indexOf("@G")!=-1){
                String[] strings=msg.split(",");
                Device device=HandUtil.CreateDevice(msg);
                Integer key=Integer.valueOf(strings[2].trim());
                device.setState(key);
                device.setName("shouhuan");
                switch (key){
                    case 1:ctx.writeAndFlush(HandUtil.joinParam("38,"+ HandUtil.GetDateString(new Date(),"yyyyMMddHHmmss")));break;//时间同步报文
                    case 2:break;//开机通告
/*                case 6:deviceDataService.insert(new DeviceData(device.get().getSerial(),new Date(),device.get().getCurrentCmd(),key));break;//轨迹报文GPS
                case 9:deviceDataService.insert(new DeviceData(device.get().getSerial(),new Date(),device.get().getCurrentCmd(),key));break;//离手判断心率为0
                case 13:deviceDataService.insert(new DeviceData(device.get().getSerial(),new Date(),device.get().getCurrentCmd(),key));device.get().setStepNumber(Integer.valueOf(strings[6]));break;//计步周期上传
                case 14:deviceDataService.insert(new DeviceData(device.get().getSerial(),new Date(),device.get().getCurrentCmd(),key));device.get().setHeartRate(Integer.valueOf(strings[6]));break;//心率周期上传
                case 43:deviceDataService.insert(new DeviceData(device.get().getSerial(),new Date(),device.get().getCurrentCmd(),key));break;//轨迹报文基站wif定位*/
                    case 44:ctx.writeAndFlush(HandUtil.joinParam("21"));break;//心跳报文
/*                case 99:deviceDataService.insert(new DeviceData(device.get().getSerial(),new Date(),device.get().getCurrentCmd(),key));device.get().setHeartRate(Integer.valueOf(strings[6]));break;//心率异常
                case 110:deviceDataService.insert(new DeviceData(device.get().getSerial(),new Date(),device.get().getCurrentCmd(),key));device.get().setPressure(strings[6]+"/"+strings[7]);break;//血压正常
                case 113:deviceDataService.insert(new DeviceData(device.get().getSerial(),new Date(),device.get().getCurrentCmd(),key));device.get().setPressure(strings[6]+"/"+strings[7]);break;//血压异常*/
                }
                template.convertAndSend("/topic/shouhuan",JSON.toJSONString(device));
            }
        }catch (Exception e){
            e.printStackTrace();
            System.out.println(msg);
        }
        System.out.println(msg);
    }


    //新客户端接入
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("有设备接入："+ctx.channel().id().asShortText());
        NettyServer.channelMap.put(ctx.channel().id().asShortText(),ctx.channel());
    }

    //客户端断开
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("客户端："+ctx.channel()+"断开连接");
        NettyServer.channelMap.forEach((key,obj)->{
            if(obj.id().asShortText().equals(ctx.channel().id().asShortText())){
                obj.writeAndFlush(WsController.count+"");
                NettyServer.channelMap.remove(ctx.channel().id().asShortText());
            }
        });
    }

    //异常
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //关闭通道
        ctx.channel().close();
        //打印异常
        cause.printStackTrace();
    }
}
